#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/11/19 11:02
# @Author : XXX
# @Site : 
# @File : main_caiji.py
# @Software: PyCharm

import sys
import os
from collections import deque
from datetime import datetime

import torch
import torch.nn as nn
import torch.optim as optim
# import torch.nn.functional as F
import random
import math
import numpy as np

import pandas as pd
import json

from func.save_mode_return import save_mode_return_action
from util.loguru_util import myLogger

from train_all_offline import  process_cdudata_neural, process_longrundata_neural, process_fsudata_neural
from util.FIFO_Stack import FIFO_Stack
from util.action_caiji_class import action_caiji

import pickle
from util.Replay_buffer import Replay_Buffer


all_stack = FIFO_Stack()





count = 0

# 设置默认值，有问题再改
last_longrun_config_dict = {
    "dryValve1": 50,
    "dryValve2": 50,
    "dryValve3": 50,
    "dryValve4": 50,
    "dryValve5": 50,
    "pumpPump": 50,
    "pumpBypassValve": 50}
last_cdu_config_dict = {'cduValve1': 50}

######################## 状态参数####################


need_control_temp = 40

########################环境状态参数###########################
from all_config import need_all_key, dryFan_action_space, cduValve1_action_space, save_memory_capacity
train_memory = Replay_Buffer(save_memory_capacity)
test_memory = Replay_Buffer(1000)
####################初始化部分#####################


action_caiji_each = action_caiji(dryFan_action_space, cduValve1_action_space)
# 初始化动作配置文件
with open(r'func\action_caiji.pkl', 'wb') as f:
    pickle.dump(action_caiji_each, f)


def train_all_online(input_data):
    global  last_cdu_config_dict, last_longrun_config_dict
    #################################### 数据预处理
    # input data
    ####################################
    global count
    if 1:
    # todo 这里的if也需要修改
    #try:

        # myLogger.info(f"len(longrun_data): {len(longrun_data)}")
        # myLogger.info(f'longrun_data: {longrun_data}')
        longrun_data = json.loads(input_data[0])
        cdu_data = json.loads(input_data[1])
        fsu_data = json.loads(input_data[2])

        # 这里是读取所有状态值，并进行筛选
        # 这里对重要状态进行筛选,带有neural的是用于进行智能的状态值的输入（离线训练）
        #longrun_sorted_dict = process_longrundata(longrun_data)
        longrun_sorted_dict_neural = process_longrundata_neural(longrun_data)
        # myLogger.info(flen(longrun_sorted_dict): {len(longrun_sorted_dict)}")
        # myLogger.info(f'longrun_sorted_dict: {longrun_sorted_dict}')
        #cdu_sorted_dict = process_cdudata(cdu_data)
        cdu_sorted_dict_neural = process_cdudata_neural(cdu_data)

        #fsu_sorted_dict = process_fsudata(fsu_data)
        fsu_sorted_dict_neural = process_fsudata_neural(fsu_data)


        #!!!!!!!!!!!!!!!!!!!!!!!
        ############# 此处为环境状态组成的字典############################
        all_sorted_dict = {**longrun_sorted_dict_neural, **cdu_sorted_dict_neural, **fsu_sorted_dict_neural}
        ############# 此处为环境状态组成的字典############################
        # !!!!!!!!!!!!!!!!!!!!!!!
        myLogger.info(f"当前状态{all_sorted_dict}")
        all_pddata = pd.Series(all_sorted_dict)

        if count % 100 == 0:
            test_memory.push(all_pddata, 1)

            with open('test_memory.pkl', 'wb') as f:
                print(f"已将test数据集缓存")
                pickle.dump(test_memory, f)
            with open('train_memory.pkl', 'wb') as f:
                print(f"已将train数据集缓存")
                pickle.dump(train_memory, f)

        else:
            train_memory.push(all_pddata, 1)

        all_stack.data_to_stack(all_pddata)
        all_previous, all_current = all_stack.transaction_data()
        ###########################################################################################################
        # 当程序液冷系统开始运行，则进行训练
        if True:

            myLogger.info(f"count******************************:{count}")

################################################在线推理部分##############################################
            # 推理部分

            all_action = save_mode_return_action()

            dryfan1 = all_action[0]
            dryfan2 = all_action[1]
            dryfan3 = all_action[2]
            dryfan4 = all_action[3]
            dryfan5 = all_action[4]
            cdu_valve = all_action[5]


            myLogger.info(f'推理部分########################################')
            myLogger.info(f'dryfan: {dryfan1, dryfan2, dryfan3, dryfan4, dryfan5}')
            myLogger.info(f'cdu_valve: {cdu_valve}')




#########################################################################################################################
#####################################此处是人工主动干预的代码##############################################




            ##  安全保护机制
            # 误差保护机制
            # if  all_current['cduTso'] > 55:
            #     myLogger.info(f"温度即将到达阈值，快速降温")
            #     dryfan = 80
            #     cdu_valve = 50



            # 参数安全检测
            def check_fan_range(fan_value):
                if fan_value <= 0:
                    return 0
                elif fan_value >= 90:
                    return 90
                return fan_value

            def check_valve_range(valve_value):
                if valve_value <= 5:
                    return 5
                elif valve_value >= 95:
                    return 95
                return valve_value

            dryfan1 = check_fan_range(dryfan1)
            dryfan2 = check_fan_range(dryfan2)
            dryfan3 = check_fan_range(dryfan3)
            dryfan4 = check_fan_range(dryfan4)
            dryfan5 = check_fan_range(dryfan5)
            cdu_valve = check_valve_range(cdu_valve)






#######################################################################################################################

            # !!这里组装参数的地方!!#
            cdu_config_dict = {"cduValve1": cdu_valve, "cduPump1": 50}
            longrun_config_dict = {
                                'dryValve1': dryfan1,
                                'dryValve2': dryfan2,
                                'dryValve3': dryfan3,
                                'dryValve4': dryfan4,
                                'dryValve5': dryfan5,

                                'pumpPump': 47,
                                "pumpBypassValve": 50
                            }

            last_cdu_config_dict = cdu_config_dict
            last_longrun_config_dict = longrun_config_dict

            count += 1
            return longrun_config_dict, cdu_config_dict


############################################# 模型保存 ################################################################



